package com.qing.expert.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qing.expert.modules.admin.entity.OperationLog;
import com.qing.expert.modules.admin.mapper.OperationLogMapper;
import com.qing.expert.modules.admin.service.AdminLogService;
import com.qing.expert.modules.admin.vo.response.OperationLogVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminLogServiceImpl implements AdminLogService {

    @Resource
    private OperationLogMapper operationLogMapper;

    @Override
    public Page<OperationLogVO> getOperationLogs(String action, Integer page, Integer size) {
        // 构建查询条件
        LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(action)) {
            wrapper.eq(OperationLog::getAction, action);
        }
        wrapper.orderByDesc(OperationLog::getCreateTime);

        // 分页查询
        Page<OperationLog> logPage = operationLogMapper.selectPage(new Page<>(page, size), wrapper);

        // 转换为VO对象
        Page<OperationLogVO> voPage = new Page<>(logPage.getCurrent(), logPage.getSize(), logPage.getTotal());
        voPage.setRecords(logPage.getRecords().stream().map(log -> {
            OperationLogVO vo = new OperationLogVO();
            BeanUtils.copyProperties(log, vo);
            return vo;
        }).collect(Collectors.toList()));

        return voPage;
    }
}